'use client';

import { toast } from '@/hooks/use-toast';
import { result } from '@/lib/utils';
import { useCosClient } from '@/providers/cos-provider';
import { deleteProduct } from '@/service/actions/product';
import type { listProductsByPage } from '@/service/query/product';
import { shopProductSearchSchema } from '@/service/query/schema/product';
import type { ProductType } from '@/service/type/product';
import type { ColumnDef } from '@tanstack/react-table';
import dayjs from 'dayjs';
import Link from 'next/link';
import { Suspense } from 'react';
import ConfirmButton from '../common/confirm-button';
import DateRangePicker from '../common/date-range-picker';
import SearchFilter from '../common/search-filter';
import TableLoading from '../common/table-loading';
import { Button } from '../ui/button';
import DataTable from '../ui/data-table';
import CreateEditProduct from './create-edit-product';

const productColumns: ColumnDef<ProductType>[] = [
  {
    accessorKey: 'id',
    header: '外卖ID',
  },
  {
    accessorKey: 'name',
    header: '外卖名称',
  },
  {
    accessorKey: 'price',
    header: '价格',
  },
  {
    accessorKey: 'description',
    header: '描述',
  },
  {
    accessorKey: 'createdAt',
    header: '创建时间',
    cell: ({ row }) => {
      const { createdAt } = row.original;
      return <div>{dayjs(createdAt).format('YYYY-MM-DD HH:mm:ss')}</div>;
    },
  },
  {
    accessorKey: 'updatedAt',
    header: '更新时间',
    cell: ({ row }) => {
      const { updatedAt } = row.original;
      return <div>{dayjs(updatedAt).format('YYYY-MM-DD HH:mm:ss')}</div>;
    },
  },
  {
    id: 'action',
    header: '操作',
    cell: ({ row }) => {
      const cosClient = useCosClient();
      return (
        <div className="py-1 flex items-center gap-1 ">
          <CreateEditProduct
            type="edit"
            preData={row.original}
            button={<Button variant="ghost">编辑</Button>}
          />
          <Link href={`/shop/product/${row.original.id}`}>
            <Button variant="ghost">详情</Button>
          </Link>
          <ConfirmButton
            title="删除"
            description="确认删除吗?"
            button={<Button variant="ghost">删除</Button>}
            onClick={async () => {
              const { error } = await deleteProduct(row.original.id);
              if (error) {
                toast({
                  variant: 'destructive',
                  title: error.message,
                });
                return result(error, error.message);
              }
              try {
                await cosClient?.delete(row.original.imageKeys);
                toast({
                  title: '删除成功',
                });
              } catch (error) {
                toast({
                  title: '部分资源删除失败',
                  variant: 'destructive',
                });
              }
              return result();
            }}
          />
        </div>
      );
    },
  },
];

export default function ProductTable({
  pageData,
}: {
  pageData: ReturnType<typeof listProductsByPage>;
}) {
  return (
    <div className="space-y-5">
      <SearchFilter
        formSchema={shopProductSearchSchema}
        defaultValues={{
          id: '',
          name: '',
          description: '',
          price: '',
          createdDateRange: undefined,
          updatedDateRange: undefined,
        }}
        formItems={[
          { name: 'id', label: '外卖ID' },
          { name: 'name', label: '外卖名称' },
          { name: 'description', label: '描述' },
          { name: 'price', label: '价格' },
          {
            name: 'createdDateRange',
            label: '创建时间',
            inputComp: DateRangePicker,
          },
          {
            name: 'updatedDateRange',
            label: '更新时间',
            inputComp: DateRangePicker,
          },
        ]}
        additionalButtons={[
          <CreateEditProduct
            key="create-edit-product"
            type="new"
            button={<Button>新建外卖</Button>}
          />,
        ]}
      />
      <Suspense fallback={<TableLoading />}>
        <DataTable<ProductType> pageData={pageData} columns={productColumns} />
      </Suspense>
    </div>
  );
}
